package com.whut.whw.personalinfo.mythings;

import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;

import com.whut.whw.R;
import com.whut.whw.base.BaseFragment;
import com.whut.whw.model.BackResult;
import com.whut.whw.model.Goods;
import com.whut.whw.util.BackResultCallback;
import com.whut.whw.util.EmptyUtils;
import com.whut.whw.util.GsonUtils;
import com.whut.whw.util.RecyclerViewUtils;
import com.zhy.http.okhttp.OkHttpUtils;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

import static com.whut.whw.constant.ConfigConsts.MYGOODS_PAGESIZE;
import static com.whut.whw.constant.ConfigConsts.MYGOODS_URL;

/**
 * <pre>
 *  desc: 已发布页面的信息展示
 *  Created by 忘尘无憾 on 2017/06/23.
 *  version:
 * </pre>
 */

public class PushFragment extends BaseFragment {

    public static PushFragment newInstance() {
        return new PushFragment();
    }

    private SwipeRefreshLayout mythings_swipe_refresh;//下拉刷新控件
    private RecyclerView mythings_recycler_view;//Recycler滚动控件
    private LinearLayoutManager layoutManager;//布局管理器
    private boolean isLoading = false;//默认未加载
    private List<Goods> informModelList;//数据集
    private MyThingsRecyclerViewAdapter myThingsRecyclerViewAdapter;//适配器

    private int currentPage = 1;
    private String yhbh;

    @Override
    public View initView(LayoutInflater inflater) {
        View rootView = inflater.inflate(R.layout.fragment_my_things, null);
        mythings_recycler_view = (RecyclerView) rootView.findViewById(R.id.mythings_recycler_view);
        mythings_swipe_refresh = (SwipeRefreshLayout) rootView.findViewById(R.id.mythings_swipe_refresh);
        mythings_swipe_refresh.setColorSchemeResources(R.color.colorPrimary);//设置刷新条颜色
        return rootView;
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        informModelList = new ArrayList<>();
        //0表示已发布
        myThingsRecyclerViewAdapter = new MyThingsRecyclerViewAdapter(context, informModelList, 0);
        layoutManager = new LinearLayoutManager(context);
        mythings_recycler_view.setLayoutManager(layoutManager);
        mythings_recycler_view.setAdapter(myThingsRecyclerViewAdapter);

        //获取用户编号
        SharedPreferences sp = context.getSharedPreferences("userinfo", Context.MODE_PRIVATE);
        yhbh = sp.getString("yhbh", "");
    }

    @Override
    public void setListener() {

        //上拉刷新操作
        mythings_recycler_view.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);

            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                loadingCheck(recyclerView);
            }
        });

        //下拉刷新操作
        mythings_swipe_refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                loadingData(true, 1);
            }
        });

        //点击监听事件
        myThingsRecyclerViewAdapter.setOnItemClickListener(new MyThingsRecyclerViewAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                getUiDelegate().toastLong("onItemClick" + position);
            }

            @Override
            public void onBtn1Click(View view, int position) {
                getUiDelegate().toastLong("onBtn1Click" + position);
            }

            @Override
            public void onBtn2Click(View view, int position) {
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setMessage(R.string.finish_goods_tip)
                        .setNegativeButton(R.string.cancel, null)
                        .setPositiveButton(R.string.mythings_finish, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                getUiDelegate().toastLong("finished");
                            }
                        }).show();
            }

            @Override
            public void onMoreClick(View view, int position) {
                showMorePopupMenu(view);
            }

        });
    }

    /**
     * 上拉刷新验证
     */
    private void loadingCheck(RecyclerView recyclerView) {
        if (RecyclerViewUtils.isVisBottom(recyclerView)) {
            //验证是否在下拉刷新
            boolean isRefreshing = mythings_swipe_refresh.isRefreshing();
            if (isRefreshing) {// SwipeRefreshLayout正在刷新
                myThingsRecyclerViewAdapter.notifyItemRemoved(myThingsRecyclerViewAdapter.getItemCount());
                return;
            }
            //判断是否加载完成，isLoading为true则表示加载完成已经到底了，false未到底
            if (!isLoading) {
                isLoading = true;
                loadingData(false, currentPage);
            }
        }
    }

    /**
     * 下拉刷新
     */
    private void refreshData() {
        currentPage = 1;//将当前页置为1

        //判断是否有用户
        if (EmptyUtils.isNotEmpty(yhbh)) {
            OkHttpUtils
                    .post()
                    .url(MYGOODS_URL)
                    .addParams("yhbh", yhbh)
                    .addParams("currentPage", "" + currentPage)
                    .addParams("pageSize", MYGOODS_PAGESIZE + "")
                    .build()
                    .execute(new BackResultCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            getUiDelegate().toastLong(e.toString());
                            Log.e("TC", e.toString());
                        }

                        @Override
                        public void onResponse(BackResult response, int id) {
                            Log.e("TC", response.isSuccess() + "--" + response.getData());

                            informModelList.clear();//清除数据

                            //如果请求成功
                            if (response.isSuccess()) {
                                List<Goods> list = GsonUtils.jsonToList(response.getData(), Goods.class);
                                if (list.size() < MYGOODS_PAGESIZE) {
                                    //已经到底了
                                    appendIsNoLoading(true);
                                } else {
                                    appendIsNoLoading(false);
                                }
                                informModelList.addAll(list);
                                currentPage++;//页面+1
                            } else {//如果下拉刷新没有数据
                                appendIsNoLoading(true);
                            }
                            myThingsRecyclerViewAdapter.notifyDataSetChanged();
                            mythings_swipe_refresh.setRefreshing(false);
                        }
                    });
        } else {
            Log.e("TC", "yhbh errror");
        }
    }

    /**
     * 上拉刷新
     */
    private void appendData() {
        if (EmptyUtils.isNotEmpty(yhbh)) {
            OkHttpUtils
                    .post()
                    .url(MYGOODS_URL)
                    .addParams("yhbh", yhbh)
                    .addParams("currentPage", "" + currentPage)
                    .addParams("pageSize", MYGOODS_PAGESIZE + "")
                    .build()
                    .execute(new BackResultCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            getUiDelegate().toastLong(e.toString());
                            Log.e("TC", e.toString());
                        }

                        @Override
                        public void onResponse(BackResult response, int id) {
                            Log.e("TC", response.isSuccess() + "--" + response.getData());
                            //如果请求成功
                            if (response.isSuccess()) {
                                List<Goods> list = GsonUtils.jsonToList(response.getData(), Goods.class);
                                if (list.size() < MYGOODS_PAGESIZE) {
                                    //已经到底了
                                    appendIsNoLoading(true);
                                } else {
                                    appendIsNoLoading(false);
                                }
                                currentPage++;//页码+1
                                informModelList.addAll(list);
                            } else {
                                appendIsNoLoading(true);
                            }
                            myThingsRecyclerViewAdapter.notifyDataSetChanged();
                        }
                    });
        } else {
            Log.e("TC", "yhbh errror");
        }
    }

    /**
     * 刷新数据
     *
     * @param loadingFlag true为下拉刷新，false为上拉刷新
     * @param pageNum
     */
    private void loadingData(final boolean loadingFlag, int pageNum) {
        //判断是否有用户
        if (EmptyUtils.isNotEmpty(yhbh)) {
            currentPage = pageNum;
            OkHttpUtils
                    .post()
                    .url(MYGOODS_URL)
                    .addParams("yhbh", yhbh)
                    .addParams("currentPage", "" + currentPage)
                    .addParams("pageSize", MYGOODS_PAGESIZE + "")
                    .build()
                    .execute(new BackResultCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            getUiDelegate().toastLong(e.toString());
                            Log.e("TC", e.toString());
                        }

                        @Override
                        public void onResponse(BackResult response, int id) {
                            Log.e("TC", response.isSuccess() + "--" + response.getData());


                            //如果请求成功
                            if (response.isSuccess()) {
                                List<Goods> list = GsonUtils.jsonToList(response.getData(), Goods.class);
                                if (list.size() < MYGOODS_PAGESIZE) {
                                    //已经到底了
                                    appendIsNoLoading(true);
                                } else {
                                    appendIsNoLoading(false);
                                }
                                if (loadingFlag) {
                                    informModelList.clear();//清除数据
                                }
                                informModelList.addAll(list);
                                currentPage++;//页面+1
                            } else {//如果下拉刷新没有数据
                                appendIsNoLoading(true);
                                if (loadingFlag) {
                                    informModelList.clear();
                                }
                            }
                            myThingsRecyclerViewAdapter.notifyDataSetChanged();
                            mythings_swipe_refresh.setRefreshing(false);
                        }
                    });
        } else {
            Log.e("TC", "yhbh errror");
        }
    }

    /**
     * 刷新操作时候判断下拉刷新状态和显示
     *
     * @param flag
     */
    private void appendIsNoLoading(boolean flag) {
        isLoading = flag;
        myThingsRecyclerViewAdapter.setFooterFlag(flag);
    }

    /**
     * 更多菜单弹框
     *
     * @param view
     */
    private void showMorePopupMenu(View view) {
        PopupMenu popupMenu = new PopupMenu(context, view);
        popupMenu.getMenuInflater().inflate(R.menu.menu_mygoods_more, popupMenu.getMenu());
        popupMenu.show();

        //设置每项点击监听
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                getUiDelegate().toastLong(item.getTitle().toString());
                return true;
            }
        });
    }
}
